package wqh.modbus;



import cn.tpson.modbus.core.ModBusDevice;
import cn.tpson.modbus.core.ModBusManager;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import wqh.domain.Device;
import wqh.global.GlobalDevice;
import wqh.global.GlobalTime;
import wqh.service.DeviceService;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import java.util.List;


public class WaterModBusServlet extends HttpServlet{


    @Override
    public void destroy() {
        super.destroy();
        ModBusManager.getInstance().release();
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        System.out.println("ModBusServlet启动。");
        System.out.println("#######################################################");
        ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:/spring/springmvc-dispatcher.xml");
        WaterDataCallBack waterDataCallBack = (WaterDataCallBack)ac.getBean("waterDataCallBack");

        ModBusManager.getInstance().setCallBack(waterDataCallBack);

        DeviceService deviceService = (DeviceService)ac.getBean("deviceService");
        List<Device> deviceList = deviceService.findAllRecord();
        if(deviceList.size() != 0){
            for(Device device : deviceList){
                if(!GlobalDevice.exist(device.getDevice_ip())){
                    ModBusDevice modBusDevice = new ModBusDevice(device.getDevice_ip(),device.getPort(), GlobalTime.getTime());
                    modBusDevice.setAddress((byte)1);
                    ModBusManager.getInstance().addDevice(modBusDevice);
                    System.out.println(device.getDevice_ip());
                }
            }
        }


    }
}
